package kr.co.sdworld.webs;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ServiceContext {
	
	private static final String		CURRENT_HTTP_REQUEST	=	"_current_http_request";
	private static final String		CURRENT_HTTP_RESPONSE	=	"_current_http_response";
	
	@SuppressWarnings("rawtypes")
	private static ThreadLocal s_ThreadLocal = new ThreadLocal(){
		protected Object initialValue() {
			return new HashMap();
		};
	};
	
	public static void initRequestAndResponse( HttpServletRequest request, HttpServletResponse response)
	{
		getLocalMap().put( CURRENT_HTTP_REQUEST, request);
		getLocalMap().put( CURRENT_HTTP_RESPONSE, response);
	}
	
	public static HttpServletRequest getRequest()
	{
		return (HttpServletRequest)getLocalMap().get( CURRENT_HTTP_REQUEST);
	}
	
	public static HttpServletResponse getResponse()
	{
		return (HttpServletResponse)getLocalMap().get( CURRENT_HTTP_REQUEST);
	}
	
	public static HttpSession getSession()
	{
		return getRequest().getSession();
	}
	
	public static String getParameter( String key)
	{
		return getRequest().getParameter( key);
	}
	
	public static String getParameter( String key, String defaultValue)
	{
		String value = getParameter( key);
		if( value == null || value.length() == 0)
		{
			return defaultValue;
		}
		
		return value;
	}
	
	public static void clear()
	{
		s_ThreadLocal.remove();
	}
	
	@SuppressWarnings("unchecked")
	public static <T>T getAttribute( String key)
	{
		return (T)getRequest().getAttribute( key);
	}
	
	@SuppressWarnings("unchecked")
	private static Map<String,Object> getLocalMap()
	{
		return (Map<String,Object>)s_ThreadLocal.get();
	}
	
	
}
